package com.umeox.zikrringtest.single_test

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.umeox.logger.UMLogger
import com.umeox.sdk_ring.RingOTAUpgradeListener
import com.umeox.sdk_ring.UMRingSdk
import com.umeox.zikrringtest.R
import com.umeox.zikrringtest.databinding.ActivitySingleTestBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.rosuh.filepicker.config.FilePickerManager
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs

class SingleTestActivity : AppCompatActivity(), RingOTAUpgradeListener {
    private var otaFile: String = ""
    private lateinit var viewModel: SingleTestViewModel
    private lateinit var mBinding: ActivitySingleTestBinding

    private lateinit var macAddress: String

    private val prayerTimeCalculator = PrayerTimeCalculator()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化 DataBinding
        mBinding = DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.activity_single_test, null, false
        )

        // 绑定生命周期管理
        mBinding.lifecycleOwner = this

        // 设置布局
        setContentView(mBinding.root)

        viewModel = ViewModelProvider(this)[SingleTestViewModel::class.java]
        macAddress = intent.getStringExtra("macAddress") ?: ""
        viewModel.initInteraction(macAddress)
        mBinding.viewmodel = viewModel

        //连接
        mBinding.layoutBase.btConnect.setOnClickListener {
            viewModel.showLoadingDialog()
            viewModel.ringProxy.connectDevice()
        }

        //断开连接
        mBinding.layoutBase.btDisConnect.setOnClickListener {
            viewModel.ringProxy.disConnectDevice()
        }

        //开始查找戒指
        mBinding.layoutBase.btStartFindDevice.setOnClickListener {
            viewModel.ringProxy.startFindDevice()
        }

        //停止查找戒指
        mBinding.layoutBase.btStopFindDevice.setOnClickListener {
            viewModel.ringProxy.stopFindDevice()
        }

        //获取电量版本信息
        mBinding.layoutBase.btGetBVInfo.setOnClickListener {
            viewModel.ringProxy.getDeviceBatteryPower()
        }

        //获取设备状态
        mBinding.layoutBase.btGetDeviceState.setOnClickListener {
            viewModel.ringProxy.getDeviceState()
        }

        //获取缓存计数数据
        mBinding.layoutBase.btGetDeviceCacheData.setOnClickListener {
            viewModel.ringProxy.getDeviceCacheData()
        }

        //翻转屏幕
        mBinding.layoutBase.btFlipScreen.setOnClickListener {
            viewModel.ringProxy.flipDeviceScreen()
        }

        //关机
        mBinding.layoutBase.btShutdown.setOnClickListener {
            viewModel.ringProxy.shutdown()
        }

        //重启/重置
        mBinding.layoutBase.btReboot.setOnClickListener {
            viewModel.ringProxy.reboot("")
        }

        //船运模式
        mBinding.layoutBase.btShipMode.setOnClickListener {
            viewModel.ringProxy.setShipNavigationMode()
        }

        //获取实时步数
        mBinding.layoutBase.btCurStep.setOnClickListener {
            viewModel.ringProxy.getCurrentStepNumber()
        }

        //获取所有睡眠数据
        mBinding.layoutBase.btAllSleep.setOnClickListener {
            viewModel.ringProxy.getAllSleepData()
        }

        //获取所有步数数据
        mBinding.layoutBase.btAllStep.setOnClickListener {
            viewModel.ringProxy.getAllStepData()
        }

        //获得设备雷达返回触发结果反馈(设备雷达才会退出测试模式)
        mBinding.layoutBase.btSc01Test1.setOnClickListener {
            viewModel.ringProxy.deviceRadarTest(true)
        }

        //获取tof数据反馈
        mBinding.layoutBase.btSc01Test2.setOnClickListener {
            viewModel.ringProxy.getTofResult()
        }

        //tof校准指令1
        mBinding.layoutBase.btSc01Test3.setOnClickListener {
            viewModel.ringProxy.tofCalibration1()
        }

        //tof校准指令2
        mBinding.layoutBase.btSc01Test4.setOnClickListener {
            viewModel.ringProxy.tofCalibration2()
        }

        mBinding.layoutBase.btSc01Data.setOnClickListener {
            viewModel.ringProxy.getAllWorshipCacheData()
        }

        var audio1Enable = false
        var audio2Enable = false

        mBinding.layoutBase.btSc01Audio1.setOnClickListener {
            audio1Enable = !audio1Enable
            audio2Enable = false
            viewModel.ringProxy.sc01SpeakerAudioTest(audio1Enable = audio1Enable,audio2Enable = false)
        }

        mBinding.layoutBase.btSc01Audio2.setOnClickListener {
            audio2Enable = !audio2Enable
            audio1Enable = false
            viewModel.ringProxy.sc01SpeakerAudioTest(audio1Enable = false,audio2Enable = audio2Enable)
        }

        var light = true

        //全亮测试指令(N01)
        mBinding.layoutBase.btN01ScreenTest.setOnClickListener {
            viewModel.ringProxy.n01ScreenTest(light)
            light = !light
        }

        //同步时间
        mBinding.layoutCore.layoutSyncTime.etTime.setText(
            SimpleDateFormat(
                "yyyyMMddHHmmssSSS",
                Locale.US
            ).format(Date())
        )

        mBinding.layoutCore.layoutSyncTime.btSyncTime.setOnClickListener {
            val is24Hour = mBinding.layoutCore.layoutSyncTime.spTime.selectedItemPosition == 0

            val etTime = mBinding.layoutCore.layoutSyncTime.etTime.text.toString()
            try {
                val date = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.US).parse(etTime)
                viewModel.ringProxy.syncCurrentTimeAndTimeFormat(
                    date,
                    is24Hour,
                    true,
                    getCurrentTimeZone()
                )
            } catch (e: Exception) {
                Toast.makeText(this, "时间格式输出错误！！！", Toast.LENGTH_SHORT).show()
            }
        }

        //同步祈祷提醒
        mBinding.layoutCore.layoutSyncChant.btSyncChant.setOnClickListener {
            val startTime = mBinding.layoutCore.layoutSyncChant.etStart.text.toString()
            val endTime = mBinding.layoutCore.layoutSyncChant.etEnd.text.toString()

            try {
                SimpleDateFormat("HH:mm", Locale.US).parse(startTime)
            } catch (e: Exception) {
                mBinding.layoutCore.layoutSyncChant.btSwitch.isChecked = false
                Toast.makeText(this, "时间格式输出错误！！！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            try {
                SimpleDateFormat("HH:mm", Locale.US).parse(endTime)
            } catch (e: Exception) {
                mBinding.layoutCore.layoutSyncChant.btSwitch.isChecked = false
                Toast.makeText(this, "时间格式输出错误！！！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val interval =
                (mBinding.layoutCore.layoutSyncChant.spInterval.selectedItem as String).replace(
                    "h",
                    ""
                ).trim().toInt()
            viewModel.ringProxy
                .setPrayerReminders(
                    mBinding.layoutCore.layoutSyncChant.btSwitch.isChecked,
                    startTime,
                    endTime,
                    interval
                )
        }

        //设置屏幕亮度
        mBinding.layoutCore.layoutSyncLight.btSyncLight.setOnClickListener {
            viewModel.ringProxy
                .setDeviceScreenBrightness(mBinding.layoutCore.layoutSyncLight.spLight.selectedItemPosition)
        }

        //设置语言
        mBinding.layoutCore.layoutSyncLanguage.btSyncLanguage.setOnClickListener {
            viewModel.ringProxy
                .setDeviceLanguage(mBinding.layoutCore.layoutSyncLanguage.spLanguage.selectedItemPosition)
        }

        //设置息屏时间
        mBinding.layoutCore.layoutSyncRestTime.btSyncRestTime.setOnClickListener {
            val time =
                mBinding.layoutCore.layoutSyncRestTime.etRestTime.text.toString().trim().toInt()
            viewModel.ringProxy.setScreenRestTime(time)
        }

        //设置祈祷配置
        mBinding.layoutCore.layoutSyncPrayerConfig.btSyncPrayerConfig.setOnClickListener {
            try {
                //晨礼
                val enable1 = if (mBinding.layoutCore.layoutSyncPrayerConfig.btSwitch1.isEnabled) {
                    1
                } else {
                    0
                }
                val offset1 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etOffsetTime1.text.toString().toInt()
                val alarmOffset1 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etAlarmOffsetTime1.text.toString()
                        .toInt()
                //晌礼
                val enable2 = if (mBinding.layoutCore.layoutSyncPrayerConfig.btSwitch2.isEnabled) {
                    1
                } else {
                    0
                }
                val offset2 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etOffsetTime2.text.toString().toInt()
                val alarmOffset2 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etAlarmOffsetTime2.text.toString()
                        .toInt()
                //晡礼
                val enable3 = if (mBinding.layoutCore.layoutSyncPrayerConfig.btSwitch3.isEnabled) {
                    1
                } else {
                    0
                }
                val offset3 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etOffsetTime3.text.toString().toInt()
                val alarmOffset3 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etAlarmOffsetTime3.text.toString()
                        .toInt()
                //昏礼
                val enable4 = if (mBinding.layoutCore.layoutSyncPrayerConfig.btSwitch4.isEnabled) {
                    1
                } else {
                    0
                }
                val offset4 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etOffsetTime4.text.toString().toInt()
                val alarmOffset4 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etAlarmOffsetTime4.text.toString()
                        .toInt()
                //宵礼
                val enable5 = if (mBinding.layoutCore.layoutSyncPrayerConfig.btSwitch5.isEnabled) {
                    1
                } else {
                    0
                }
                val offset5 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etOffsetTime5.text.toString().toInt()
                val alarmOffset5 =
                    mBinding.layoutCore.layoutSyncPrayerConfig.etAlarmOffsetTime5.text.toString()
                        .toInt()

                val configs = Array(5) {
                    Array(3) {
                        0
                    }
                }
                configs[0][0] = enable1
                configs[0][1] = offset1
                configs[0][2] = alarmOffset1
                configs[1][0] = enable2
                configs[1][1] = offset2
                configs[1][2] = alarmOffset2
                configs[2][0] = enable3
                configs[2][1] = offset3
                configs[2][2] = alarmOffset3
                configs[3][0] = enable4
                configs[3][1] = offset4
                configs[3][2] = alarmOffset4
                configs[4][0] = enable5
                configs[4][1] = offset5
                configs[4][2] = alarmOffset5
                viewModel.ringProxy.setPrayerRemindConfig(configs)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        //同步计数模式
        mBinding.layoutCore.layoutSyncCountMode.btSyncCountMode.setOnClickListener {
            try {
                val normal33 = mBinding.layoutCore.layoutSyncCountMode.btSwitch33.isChecked
                val normal100 = mBinding.layoutCore.layoutSyncCountMode.btSwitch100.isChecked
                val customValue =
                    mBinding.layoutCore.layoutSyncCountMode.etCustomValue.text.toString().toInt()
                viewModel.ringProxy.setCustomCountReminder(normal33, normal100, customValue)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        //设置祈祷提醒
        mBinding.layoutCore.layoutSyncPrayer.btSyncPrayer.setOnClickListener {
            try {
                val fa = mBinding.layoutCore.layoutSyncPrayer.etFajrAngle.text.toString().toFloat()
                val ms: Float =
                    mBinding.layoutCore.layoutSyncPrayer.etMaghribIsMinutes.text.toString()
                        .toFloat()
                val mv: Float =
                    mBinding.layoutCore.layoutSyncPrayer.etMaghribValue.text.toString().toFloat()
                val isha: Float =
                    mBinding.layoutCore.layoutSyncPrayer.etIshaIsMinutes.text.toString().toFloat()
                val iv: Float =
                    mBinding.layoutCore.layoutSyncPrayer.etIshaValue.text.toString().toFloat()

                val factions =
                    mBinding.layoutCore.layoutSyncPrayer.etFactions.text.toString().toInt()
                val timeZone =
                    mBinding.layoutCore.layoutSyncPrayer.etTimeZone.text.toString().toDouble()
                val latitude =
                    mBinding.layoutCore.layoutSyncPrayer.etLatitude.text.toString().toDouble()
                val longitude =
                    mBinding.layoutCore.layoutSyncPrayer.etLongitude.text.toString().toDouble()

                if (mBinding.layoutCore.layoutSyncPrayer.btPrayer.isChecked) {
                    lifecycleScope.launch {
                        viewModel.ringProxy
                            .setCustomizeConvention(fa, ms == 1.0f, mv, isha == 1.0f, iv)
                        delay(2000)
                        viewModel.ringProxy
                            .setPrayerRemindersState(
                                true,
                                21,
                                factions,
                                latitude,
                                longitude,
                                timeZone
                            )
                    }
                } else {
                    viewModel.ringProxy
                        .setPrayerRemindersState(false, 0, 0, 0.0, 0.0, 0.0)
                }

                val date = mBinding.layoutCore.layoutSyncTime.etTime.text.toString()
                val parseDate = SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA).parse(date)

                val prayerList = prayerTimeCalculator.getPrayerList(
                    doubleArrayOf(
                        fa.toDouble(), ms.toDouble(),
                        mv.toDouble(), isha.toDouble(), iv.toDouble()
                    ), factions, timeZone, latitude, longitude, parseDate!!
                )
                mBinding.layoutCore.layoutSyncPrayer.tvPrayerTime.text = prayerList.joinToString()
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this, "数据格式不正确！！！", Toast.LENGTH_SHORT).show()
            }
        }

        mBinding.layoutCore.layoutSyncUserInfo.btSyncUserInfo.setOnClickListener {
            val age = mBinding.layoutCore.layoutSyncUserInfo.etAge.text.toString().toInt()
            val gender = if (mBinding.layoutCore.layoutSyncUserInfo.btGender.isChecked) {
                0
            } else {
                1
            }
            val height = mBinding.layoutCore.layoutSyncUserInfo.etHeight.text.toString().toInt()
            val weight = mBinding.layoutCore.layoutSyncUserInfo.etWeight.text.toString().toInt()
            val hrMax = mBinding.layoutCore.layoutSyncUserInfo.etHrMax.text.toString().toInt()
            val hrRest = mBinding.layoutCore.layoutSyncUserInfo.etHrRest.text.toString().toInt()
            val vo2max = mBinding.layoutCore.layoutSyncUserInfo.etVo2max.text.toString().toInt()
            viewModel.ringProxy
                .setUserInfo(age, gender, height, weight, hrMax, hrRest, vo2max)
        }

        viewModel.pkeyObserver.observe(this) {
            mBinding.layoutCore.layoutSyncPkey.etPkey.setText(it)
        }

        mBinding.layoutCore.layoutSyncPkey.etMacAddress.setText(macAddress)

        //Pkey值
        mBinding.layoutCore.layoutSyncPkey.btSyncPkey.setOnClickListener {
            val pkey = mBinding.layoutCore.layoutSyncPkey.etPkey.text.toString()
            var newMacAddress = mBinding.layoutCore.layoutSyncPkey.etMacAddress.text.toString()

            if (!(pkey.length == 64 || pkey.isEmpty())) {
                UMRingSdk.log("App", "pkey = $pkey")
                Toast.makeText(this, "PKey值格式错误!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (!newMacAddress.contains(":")) {
                if (newMacAddress.length != 12) {
                    UMRingSdk.log("App", "newMacAddress = $newMacAddress")
                    Toast.makeText(this, "无效的蓝牙地址!", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                val toCharArray = newMacAddress.toCharArray()
                newMacAddress =
                    "${toCharArray[0]}${toCharArray[1]}:${toCharArray[2]}${toCharArray[3]}:${toCharArray[4]}${toCharArray[5]}:${toCharArray[6]}${toCharArray[7]}:${toCharArray[8]}${toCharArray[9]}:${toCharArray[10]}${toCharArray[11]}"
            }

            if (!BluetoothAdapter.checkBluetoothAddress(newMacAddress.uppercase(Locale.getDefault()))) {
                UMRingSdk.log("App", "newMacAddress = $newMacAddress")
                Toast.makeText(this, "无效的蓝牙地址!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            lifecycleScope.launch {
                viewModel.ringProxy.pkeyOperation(true, pkey)
                delay(1000)
                viewModel.ringProxy.reboot(newMacAddress)
            }


        }

        //设置时间显示类型
        mBinding.layoutCore.layoutSetTimeShowType.btSetTimeShowType.setOnClickListener {
            val type = mBinding.layoutCore.layoutSetTimeShowType.spTimeShowType.selectedItemPosition
            viewModel.ringProxy.setTimeShowType(type)
        }

        //获取SC01设备信息
        mBinding.layoutBase.btGetSc01Info.setOnClickListener {
            viewModel.ringProxy.getSc01DeviceInfo()
        }

        mBinding.layoutCore.layoutSyncSc01Audio.btSyncSc01AudioEnable.setOnClickListener {
            val sc01AudioEnable = mBinding.layoutCore.layoutSyncSc01Audio.btSwitch.isChecked
            Log.d("xcl_debug", "onCreate: sc01AudioEnable = $sc01AudioEnable")
            viewModel.ringProxy.setSc01AudioEnable(sc01AudioEnable)
        }

        //选择文件
        mBinding.layoutOta.btSelectFile.setOnClickListener {
            FilePickerManager
                .from(this)
                .enableSingleChoice()
                .registerFileType(arrayListOf(OTAFileType()), true)
                .forResult(100)
        }

        //OTA升级
        mBinding.layoutOta.btOTA.setOnClickListener {
            if (otaFile.isNotEmpty()) {
                Toast.makeText(this, "准备升级...", Toast.LENGTH_SHORT).show()
                viewModel.showLoadingDialog()
                viewModel.ringProxy.startOTAUpgrade(File(otaFile), true, this)
            } else {
                Toast.makeText(this, "请先选择OTA升级文件", Toast.LENGTH_SHORT).show()
            }
        }

        //汇顶OTA升级
        mBinding.layoutOta.btHdOTA.setOnClickListener {
            if (otaFile.isNotEmpty()) {
                Toast.makeText(this, "准备升级...", Toast.LENGTH_SHORT).show()
                viewModel.showLoadingDialog()
                viewModel.ringProxy.startHDOTAUpgrade(File(otaFile), this)
            } else {
                Toast.makeText(this, "请先选择OTA升级文件", Toast.LENGTH_SHORT).show()
            }
        }

        initTaskConfig()
    }

    /**
     * 可简化计算过程 为了方便理解 没有简化
     */
    private fun getCurrentTimeZone(): Double {
        val now = Date()
        val zone = TimeZone.getDefault()
        val id = zone.id
        val timeZone1 = TimeZone.getTimeZone(id)
        val timeZone2 = TimeZone.getTimeZone("UTC")

        val currentOffsetFromUTC = if (timeZone1.inDaylightTime(now)) {
            timeZone1.dstSavings + timeZone1.rawOffset
        } else {
            0 + timeZone1.rawOffset
        }

        val serverOffsetFromUTC = if (timeZone2.inDaylightTime(now)) {
            timeZone2.dstSavings + timeZone2.rawOffset
        } else {
            0 + timeZone2.rawOffset
        }

        val isNegativeNumber = currentOffsetFromUTC < 0

        val secondOffset = abs(abs(serverOffsetFromUTC) - currentOffsetFromUTC) / 1000
        val hour = secondOffset / 3600
        val minute = secondOffset % 3600 / 60
        return if (isNegativeNumber) {
            -1.0 * (hour + minute / 60.0)
        } else {
            hour + minute / 60.0
        }
    }

    private var taskRunning = false

    /**
     * 正常任务执行
     * 主动中断
     * 被动中断
     */
    private fun initTaskConfig() {
        mBinding.layoutCore.layoutTaskTest.btStartTask.setOnClickListener {
            try {
                val etTargetNumber =
                    mBinding.layoutCore.layoutTaskTest.etTargetNumber.text.toString().toInt()
                val etTaskId = mBinding.layoutCore.layoutTaskTest.etTaskId.text.toString().toInt()
                viewModel.setTask(etTargetNumber, etTaskId)
                viewModel.ringProxy.setTasbihTask(true, etTargetNumber, etTaskId)
                taskRunning = true
            } catch (e: Exception) {
                Toast.makeText(this, "数据格式错误!!!", Toast.LENGTH_SHORT).show()
            }
        }

        mBinding.layoutCore.layoutTaskTest.btEndTask.setOnClickListener {
            if (!taskRunning) {
                Toast.makeText(this, "当前没有任务在进行！！！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            viewModel.ringProxy.setTasbihTask(false, 0, 0)
            taskRunning = false
        }


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            100 -> {
                if (resultCode == RESULT_OK && data != null) {
                    val list = FilePickerManager.obtainData()
                    if (!list.isNullOrEmpty()) {
                        otaFile = list[0]
                        mBinding.layoutOta.tvFilePath.text = otaFile
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.ringProxy.destroy()
    }

    override fun upgradeFail() {
        runOnUiThread {
            Toast.makeText(this, "升级失败", Toast.LENGTH_SHORT).show()
            viewModel.hideLoadingDialog()
        }
    }

    override fun upgradeSuccessful() {
        runOnUiThread {
            Toast.makeText(this, "升级成功", Toast.LENGTH_SHORT).show()
            viewModel.hideLoadingDialog()
        }
    }

    override fun upgradeStart() {
        runOnUiThread {
            Toast.makeText(this, "开始升级", Toast.LENGTH_SHORT).show()
        }
    }

    override fun upgradeProgress(progress: Int) {
        runOnUiThread {
            Toast.makeText(this, "升级中 $progress %", Toast.LENGTH_SHORT).show()
        }
    }
}